package com.nuoniu.sibanyun.service.crm.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.nuoniu.sibanyun.common.exception.NuoNiuException;
import com.nuoniu.sibanyun.common.lang.StringUtils;
import com.nuoniu.sibanyun.entity.SendSms;
import com.nuoniu.sibanyun.entity.SysEmployee;
import com.nuoniu.sibanyun.entity.SysUser;
import com.nuoniu.sibanyun.entity.crm.*;
import com.nuoniu.sibanyun.mapper.crm.CrmInvitationFormMapper;
import com.nuoniu.sibanyun.service.ISendSmsService;
//import com.nuoniu.sibanyun.service.ISysEmployeeService;
import com.nuoniu.sibanyun.service.ISysUserService;
import com.nuoniu.sibanyun.service.crm.*;
import com.nuoniu.sibanyun.service.impl.SysUserServiceImpl;
import com.nuoniu.sibanyun.service.redis.RedisService;
import com.nuoniu.sibanyun.userThread.UserInfo;
import com.nuoniu.sibanyun.userThread.UserThreadLocal;
import com.nuoniu.sibanyun.utils.IpUtil;
import com.nuoniu.sibanyun.utils.SendSmsUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 邀约表单 服务实现类
 * </p>
 *
 * @author 小啊刚
 * @since 2021-09-03
 */
@Service
public class CrmInvitationFormServiceImpl extends ServiceImpl<CrmInvitationFormMapper, CrmInvitationForm> implements ICrmInvitationFormService {

    @Autowired
    private ICrmCustomerService crmCustomerService;
    @Autowired
    private ICrmLinkmanService linkmanService;
    @Autowired
    private ICrmBusinessService businessService;
    @Autowired
    private ICrmFormService formService;
    @Autowired
    private ICrmFormFieldService formFieldService;
    @Autowired
    private RedisService redisService;
    @Autowired
    private ISendSmsService sendSmsService;
    @Autowired
    private SysUserServiceImpl sysUserService;
//    @Autowired
//    private ISysEmployeeService employeeService;

    @Override
    public Page<CrmInvitationForm> pageList(Page page, CrmInvitationForm invitationForm) {
        UserInfo userInfo = UserThreadLocal.get();
        invitationForm.setCompanyId(userInfo.getCompanyId());
        return baseMapper.pageList(page, invitationForm);
    }

    @Override
    @Transactional
    public void saveForm(CrmInvitationForm invitationForm) {
        CrmForm form = formService.getById(invitationForm.getFormId());

        if(form == null) {
            throw new NuoNiuException("网络异常,请联系管理员");
        }

        if(form.getIsSms().equals(1)) { //校验短信验证码
            Object smsCode = redisService.get("invitation_" + invitationForm.getPhone());
            if(smsCode == null || !invitationForm.getSmsCode().equals(smsCode.toString())) {
                throw new NuoNiuException("短信验证码不正确");
            }
        }

        CrmInvitationForm formData = baseMapper.getByPhone(invitationForm);
        if(formData != null) {
            throw new NuoNiuException("此手机号已使用");
        }

        if(invitationForm.getId() == null && StringUtils.isNotBlank(invitationForm.getCrmName())) {
            SysUser employee = sysUserService.getByUserId(invitationForm.getShareUserId().longValue());
            if(employee == null || !(employee.getCompanyId().equals(form.getCompanyId().longValue()))) {
                throw new NuoNiuException("网络异常,请联系管理员");
            }

            invitationForm.setCompanyId(form.getCompanyId());
            invitationForm.setShareUserName(employee.getRealName());

            //CRM处理
            CrmCustomer customer = crmCustomerService.checkName(invitationForm.getCrmName(), form.getCompanyId());
            if(customer == null) {
                customer = new CrmCustomer();
                customer.setCrmName(invitationForm.getCrmName());
                customer.setCompanyId(form.getCompanyId());
                customer.setCrmType(1);
                customer.setType("客户");
                customer.setCrmSource("市场活动");
                customer.setIsCustomer(true);
                customer.setMobile(invitationForm.getPhone());
                customer.setPhone(invitationForm.getPhone());
                customer.setCrmNo(crmCustomerService.getCustomerNo(form.getCompanyId()));
                customer.setCreateUserId(form.getCreateUserId());
                customer.setCreateUserName(form.getCreateUserName());
                //直接领用
                customer.setCollarUserId(employee.getId().intValue());
                customer.setCollarUserName(employee.getRealName());
                customer.setCollarTime(LocalDateTime.now());
                customer.setOfficeId(employee.getOfficeId().intValue());
                customer.setOfficeName(employee.getOfficeName());
                crmCustomerService.save(customer);
            }

            if(customer.getId() != null) {
                if(customer.getCrmType().equals(0)) {
                    //直接领用
                    customer.setCrmType(1);
                    customer.setCollarUserId(employee.getId().intValue());
                    customer.setCollarUserName(employee.getRealName());
                    customer.setCollarTime(LocalDateTime.now());
                    customer.setOfficeId(employee.getOfficeId().intValue());
                    customer.setOfficeName(employee.getOfficeName());
                    crmCustomerService.updateById(customer);
                }

                //新增联系人
                if(StringUtils.isNotBlank(invitationForm.getName())) {
                    CrmLinkman linkman = linkmanService.getByName(invitationForm.getName(), customer.getId());
                    if(linkman == null) {
                        linkman = new CrmLinkman();
                        linkman.setCompanyId(form.getCompanyId());
                        linkman.setCrmId(customer.getId().intValue());
                        linkman.setCrmName(customer.getCrmName());
                        linkman.setName(invitationForm.getName());
                        linkman.setMobile(invitationForm.getPhone());
                        linkman.setQq(invitationForm.getQq());
                        linkman.setEmail(invitationForm.getEmail());
                        linkman.setWeixin(invitationForm.getWeChat());
                        linkman.setContactAddress(invitationForm.getAddress());
                        linkman.setCreateUserId(form.getCreateUserId());
                        linkman.setCreateUserName(form.getCreateUserName());
                        linkmanService.save(linkman);
                    }
                }

                //新增商机
                CrmBusiness business = new CrmBusiness();
                business.setCompanyId(form.getCompanyId());
                business.setActivityId(form.getActivityId());
                business.setActivityName(form.getActivityName());
                business.setTitle(form.getTitle());
                business.setCrmId(customer.getId().intValue());
                business.setCrmName(customer.getCrmName());
                business.setCreateUserId(form.getCreateUserId());
                business.setCreateUserName(form.getCreateUserName());
                business.setTitle("活动邀约");
                business.setProjectNo(businessService.getBusinessNo(form.getCompanyId()));
                businessService.save(business);
            }
        }

        this.saveOrUpdate(invitationForm);
    }

    @Override
    public void deleteFormData(Long id) {
        this.removeById(id);
    }

    @Override
    public String getInvitationUrl(Long id) {
        return null;
    }

    @Override
    public void deleteForm(Long formId) {
        formService.removeById(formId);
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("form_id", formId);
        formFieldService.remove(wrapper);
    }

    @Override
    public CrmForm getDetail(Long id) {
        CrmForm form = formService.getById(id);
        form.setFields(formFieldService.getFormFieldList(id));
        return form;
    }

    @Override
    public void sendSms(CrmInvitationForm invitationForm, HttpServletRequest request) {
        CrmForm form = formService.getById(invitationForm.getFormId());
        if(!form.getIsSms().equals(1)) {
            throw new NuoNiuException("此表单未开通验证码功能");
        }

        CrmInvitationForm formData = baseMapper.getByPhone(invitationForm);
        if(formData != null) {
            throw new NuoNiuException("此手机号已使用");
        }

        String userPhone = invitationForm.getPhone();
        String ip = IpUtil.getClientIp(request);
        Object code = redisService.get("invitation_" + userPhone + "_" + ip);
        if(code == null || !(code.toString().toLowerCase().equals(invitationForm.getImgCode().toLowerCase()))) {
            throw new NuoNiuException("图片验证码不正确");
        }

        if(redisService.hasKey("check_invitation_" + userPhone)) {
            throw new NuoNiuException("请勿频繁发送验证码");
        }

        Integer count = sendSmsService.countByCompany(form.getCompanyId());
        if(count >= 10) {
            throw new NuoNiuException("今日发送次数已上限");
        }

        Map<String, Object> data = SendSmsUtils.sentSms(userPhone);
        String result = data.get("result").toString();
        if ("success".equals(result)) {
            redisService.set("check_invitation_" + userPhone, "1", 60);
            String smsCode = data.get("code").toString();
            //验证码保存到redis中
            redisService.set("invitation_" + userPhone, smsCode, 900);
            //保存发送记录
            SendSms sendSms = new SendSms();
            sendSms.setPhone(userPhone);
            sendSms.setCode(smsCode);
            sendSms.setType(1);
            sendSms.setCompanyId(form.getCompanyId());
            sendSms.setRemarks("表单邀约");
            sendSms.setIp(IpUtil.getClientIp(request));
            sendSmsService.save(sendSms);
        } else {
            throw new NuoNiuException("发送失败");
        }
    }
}
